from decorator import decorator


from cibynet.lib.base import *
from cibynet.model import utils as m_utils


def UserIsAuthenticated():
  """Returns True if the user is authenticated, False otherwise.
  """
  return request.environ.get('repoze.who.identity') is not None

  
def UserInGroup(trusted_group):
  """Will abort if the logged in user doesn't belong to trusted_group.
  
  Arguments:
    - trusted_group: string, name of the group you want to grant access.
    
  TODO: let specify more than one group.
  """
  identity = request.environ.get('repoze.who.identity')
  if identity is None:
    abort(401)
  if trusted_group not in identity['groups']:
    abort(403)


def UserIs(user):
  """Will abort if the logged in user is not the one specified.
  """
  identity = request.environ.get('repoze.who.identity')
  if identity is None:
    abort(401)
  if user is not identity['user']:
    abort(403)
  

def UserInGroupD(trusted_group):
  """Same as UserInGroup but in decorator version.
  """
  @decorator
  def wrapper(f, *args, **kwargs):
    UserInGroup(trusted_group)
    return f(*args, **kwargs)
  return wrapper